package com.dempsey.gateway.service;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.dempsey.api.model.LoginUser;
import com.dempsey.common.security.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * 2. 从AuthenticationToken读取Token并做用户数据解析
 *
 * @author zhe.xiao
 * @date 2021-04-14 23:35
 * @description
 */
@Component
public class ScAuthenticationManager implements ReactiveAuthenticationManager {

    private final static Log log = LogFactory.get();

    @Autowired
    private TokenService tokenService;

    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {
        log.info("2. 从AuthenticationToken读取Token并做用户数据解析");

        String tokenString = (String) authentication.getPrincipal();
        log.info(tokenString);

        //校验token
        LoginUser loginUser = tokenService.getLoginUserByToken(tokenString);
        log.info("loginUser：{}", loginUser);

        return Mono.just(authentication).map(auth -> new UsernamePasswordAuthenticationToken(loginUser, null, null));
    }

}